package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
)

func sendChatMessage(message string) (string, error) {
	apiKey := API_KEY
	url := URL

	requestBody := RequestBody{
		Model: "qwen-plus",
		Input: Input{
			Messages: []Message{
				{
					Role:    "system",
					Content: "",
				},
				{
					Role:    "user",
					Content: message,
				},
			},
		},
		Parameters: Parameters{
			ResultFormat:   "message",
			TopP:           0.8,
			Temperature:    0.7,
			EnableSearch:   false,
			EnableThinking: false,
			ThinkingBudget: 4000,
		},
	}

	jsonBody, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Println("Error marshaling request body:", err)
		return "", err
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return "", err
	}

	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-DashScope-SSE", "enable")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return "", err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return "", err
	}
	// fmt.Println("原始响应：\n", string(body))
	content, err := parseResponse(body)
	if err != nil {
		fmt.Println("Error parsing response:", err)
		return "", err
	}

	// fmt.Println("=============回复=============：\n", content)
	return content, err
}

func sendChatMessageAndRule(message string, systemContent string) (string, error) {
	apiKey := API_KEY
	url := URL

	requestBody := RequestBody{
		Model: "qwen-plus",
		Input: Input{
			Messages: []Message{
				{
					Role:    "system",
					Content: systemContent,
				},
				{
					Role:    "user",
					Content: message,
				},
			},
		},
		Parameters: Parameters{
			ResultFormat:   "message",
			TopP:           0.8,
			Temperature:    0.7,
			EnableSearch:   false,
			EnableThinking: false,
			ThinkingBudget: 4000,
		},
	}

	jsonBody, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Println("Error marshaling request body:", err)
		return "", err
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return "", err
	}

	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-DashScope-SSE", "enable")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return "", err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return "", err
	}
	// fmt.Println("原始响应：\n", string(body))
	content, err := parseResponse(body)
	if err != nil {
		fmt.Println("Error parsing response:", err)
		return "", err
	}

	// fmt.Println("=============回复=============：\n", content)
	return content, err
}

func parseResponse(body []byte) (string, error) {
	// 分割字符串获取JSON部分
	parts := strings.Split(string(body), "data:")
	jsonStr := parts[len(parts)-1]

	var dataJson Data
	err := json.Unmarshal([]byte(jsonStr), &dataJson)
	if err != nil {
		return "", err
	}
	// fmt.Println("解析后的JSON：\n", dataJson)
	content := dataJson.Output.Choices[0].Message.Content
	// fmt.Println("解析后的内容：\n", content)
	return content, err
}
